package com.wnhz.work.jy.fragment;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.solidfire.gson.Gson;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.MyMain;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.activity.ChoosePayActivity;
import com.wnhz.work.jy.adapter.ShoppingAdapter;
import com.wnhz.work.jy.bean.ShoppingBean;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * ----购物车
 */
@ContentView(R.layout.homefragment4)
public class HomeFragment4 extends Fragment {
    private static final String TAG = "HomeFragment4";
    @ViewInject(R.id.view_main_middle_title)
    private TextView title;
    @ViewInject(R.id.view_main_right_text)
    private TextView right;

    @ViewInject(R.id.allSelect)
    private ImageView allSelect;

    @ViewInject(R.id.tv_true)
    private TextView tv_true;

    @ViewInject(R.id.include_shopping_null)
    private View include_shopping_null;//购物车为空
    @ViewInject(R.id.rl_shopping)
    private RelativeLayout rl_shopping;//底部的栏
    @ViewInject(R.id.lv_shopping)
    private ListView lv_shopping;
    private ArrayList<ShoppingBean> shopList = new ArrayList<>();
    private ArrayList<ShoppingBean> selectshopList = new ArrayList<>();

    private ShoppingAdapter mAdapter;
    private boolean isAllSelect = false;
    @ViewInject(R.id.qx)
    private TextView qx;
    private MyMain myMain;


    @ViewInject(R.id.tv_all_price)
    private TextView tv_all_price;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /*view = inflater.inflate(R.layout.homefragment4, container, false);
        initData();
        initView();*/
        myMain = (MyMain) getActivity();
        return x.view().inject(this, inflater, container);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }


    @ViewInject(R.id.btn_main_left)
    private View btn_main_left;
    @ViewInject(R.id.btn_main_right)
    private View btn_main_right;
    @ViewInject(R.id.view_main_right_text)
    private View view_main_right_text;


    private void initView() {
        title.setText("购物车");
        btn_main_left.setVisibility(View.GONE);
        btn_main_right.setVisibility(View.VISIBLE);
        view_main_right_text.setVisibility(View.VISIBLE);
        /*view.findViewById(R.id.btn_main_right).setOnClickListener(this);
        view.findViewById(R.id.rl_all_selector).setOnClickListener(this);
        view.findViewById(R.id.tv_true).setOnClickListener(this);*/

        /*right = (TextView) view.findViewById(R.id.view_main_right_text);
        lv_shopping = (ListView) view.findViewById(R.id.lv_shopping);
        allSelect = (ImageView) view.findViewById(R.id.allSelect);
        tv_true = (TextView) view.findViewById(R.id.tv_true);
        include_shopping_null = view.findViewById(R.id.include_shopping_null);//购物车为空
        rl_shopping = (RelativeLayout) view.findViewById(R.id.rl_shopping);//底部的栏*/

        right.setText("编辑");

        mAdapter = new ShoppingAdapter(getActivity(), shopList, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent;
                final int index;
                switch (view.getId()) {

                    //选择
                    case R.id.rl_selector:

                        index = (Integer) view.getTag();
                        if ("1".equals(shopList.get(index).getIsEnough())) {
                            shopList.get(index).setSelect(!shopList.get(index).isSelect());
                            isAllSelect = true;
                            setAllSelect();
                        } else {
                            Toast.makeText(getActivity(), "库存不足，无法选择", Toast.LENGTH_SHORT).show();
                        }

//                Toast.makeText(getActivity(), "选中", Toast.LENGTH_SHORT).show();
                        break;


                    //删除
                    case R.id.tv_delete:
                        index = (Integer) view.getTag();
                        int size = shopList.size();
                        new AlertDialog.Builder(getActivity()).setTitle("")//设置对话框标题
                                .setMessage("你确定删除该商品吗？")//设置显示的内容
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                        removeCart(index);


                                    }
                                }).setNegativeButton("返回", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).show();

                        break;

                    //减少数目
                    case R.id.tv_minus:
                        index = (Integer) view.getTag();
                        int numSub = Integer.parseInt(shopList.get(index).getGoodNumber());
                        if (numSub == 1) {
                            Toast.makeText(getActivity(), "再减就没了", Toast.LENGTH_SHORT).show();
                        } else {
                            shopList.get(index).setGoodNumber((numSub - 1) + "");
                        }
                        break;

                    //增加数目
                    case R.id.tv_add:
                        index = (Integer) view.getTag();
                        int numAdd = Integer.parseInt(shopList.get(index).getGoodNumber());
                        shopList.get(index).setGoodNumber((numAdd + 1) + "");
                        break;

                    default:
                        break;
                }

                updateAllPrice();
                mAdapter.notifyDataSetChanged();
            }
        });

        lv_shopping.setAdapter(mAdapter);


    }

    private void setAllSelect() {

        for (int i = 0; i < shopList.size(); i++) {
            if (shopList.get(i).isSelect() == false) {
                isAllSelect = false;
                break;
            }
        }
        setAllSelecttype();
    }

    @Event(value = {R.id.btn_main_right, R.id.rl_all_selector, R.id.tv_true})
    private void myClick(View view) {
        Intent intent;
        final int index;
        switch (view.getId()) {
            //编辑
            case R.id.btn_main_right:
                wancheng();
                break;


            // 全选
            case R.id.rl_all_selector:
                isAllSelect = !isAllSelect;
//                idList.clear();


//                setAllSelecttype();

                for (int i = 0; i < shopList.size(); i++) {
                    if ("1".equals(shopList.get(i).getIsEnough())) {
                        if (isAllSelect) {
                            shopList.get(i).setSelect(true);
                        } else {
                            shopList.get(i).setSelect(false);
                        }
                    }else {
                        shopList.get(i).setSelect(false);
                        Toast.makeText(getActivity(), "有部分商品库存不足，无法全选", Toast.LENGTH_SHORT).show();
                    }

                }

                setAllSelect();
/*
                for (int i = 0; i < shopList.size(); i++) {
                    if (isAllSelect == true) {
                        shopList.get(i).setSelect(true);

                    } else {
                        shopList.get(i).setSelect(false);
                    }
                }
*/
                updateAllPrice();
                mAdapter.notifyDataSetChanged();
                break;

            //下单
            case R.id.tv_true:
                if ("完成".equals(right.getText().toString())) {
                    Toast.makeText(getActivity(), "请先点击完成", Toast.LENGTH_SHORT).show();
                } else {
                    selectshopList.clear();
                    for (int i = 0; i < shopList.size(); i++) {
                        if (shopList.get(i).isSelect()) {
                            selectshopList.add(shopList.get(i));
                        }
                    }
                    if (selectshopList.size() == 0) {
                        Toast.makeText(getActivity(), "请选择要购买的商品", Toast.LENGTH_SHORT).show();
                    } else {
                        intent = new Intent(getActivity(), ChoosePayActivity.class);
                        intent.putExtra("list", selectshopList);
                        intent.putExtra("allPrice", allPrice);
                        startActivity(intent);
                    }

                }
                break;

            default:
                break;
        }
        mAdapter.notifyDataSetChanged();
    }

    private void wancheng() {
        mAdapter.setEdit(!mAdapter.isEdit());
        if (mAdapter.isEdit()) {
            right.setText("完成");
            tv_true.setBackgroundColor(0xffd9d9d9);

        } else {
            right.setText("编辑");
            edit_cart_num();
            tv_true.setBackgroundColor(0xffe2bb0a);
        }
        onHas();
    }

    private void setAllSelecttype() {
        updateAllPrice();
        if (isAllSelect) {
            qx.setText("全选");
            allSelect.setImageResource(R.mipmap.ic_xuanze31_li);
        } else {
            qx.setText("全选");
            allSelect.setImageResource(R.mipmap.ic_xuanze_nor);
        }
    }

    public boolean isediting() {
        if ("完成".equals(right.getText().toString())) {
            Toast.makeText(getActivity(), "请先点击完成", Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }


    @Override
    public void onResume() {
        mAdapter.notifyDataSetChanged();
        /*if (shopList.size() > 0) {
            lv_shopping.setVisibility(View.VISIBLE);
            rl_shopping.setVisibility(View.VISIBLE);
            include_shopping_null.setVisibility(View.GONE);
            right.setVisibility(View.VISIBLE);
        } else {
            right.setVisibility(View.GONE);
            lv_shopping.setVisibility(View.GONE);
            rl_shopping.setVisibility(View.GONE);
            include_shopping_null.setVisibility(View.VISIBLE);
        }*/
        home4getData();
        super.onResume();
    }

    public void onHas() {
        if (shopList.size() > 0) {
            right.setVisibility(View.VISIBLE);
            lv_shopping.setVisibility(View.VISIBLE);
            rl_shopping.setVisibility(View.VISIBLE);
            include_shopping_null.setVisibility(View.GONE);
        } else {
            right.setVisibility(View.GONE);
            lv_shopping.setVisibility(View.GONE);
            rl_shopping.setVisibility(View.GONE);
            include_shopping_null.setVisibility(View.VISIBLE);
        }
    }


    private void removeCart(final int index) {
        Map<String, Object> map = new HashMap<>();
        map.put("goodId", shopList.get(index).getGoodId());
        myMain.showDialog();
        map.put("userId", MyApplication.getInstance().userBean.getUserId());
        XUtil.Post(ConfigUtil.DEL_CART, map, new MyCallBack<String>() {

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess: " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String info = jsonObject.optString("info");
                    myMain.MyToast(info);
                    String re = jsonObject.optString("result");
                    if ("1".equals(re)) {
                        shopList.remove(index);
                        mAdapter.notifyDataSetChanged();
                    }

                    if (shopList.size()== 0){
                        wancheng();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFinished() {
                myMain.closeDialog();
                super.onFinished();
            }
        });
    }

    public void edit_cart_num() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", MyApplication.getInstance().userBean.getUserId());
        for (int i = 0; i < shopList.size(); i++) {
            map.put(shopList.get(i).getCartId(), shopList.get(i).getGoodNumber());
        }
        myMain.showDialog();
        XUtil.Post(ConfigUtil.EDIT_CART_NUM, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);

                Log.i(TAG, "onSuccess: edit_cart_num  " + result);
                home4getData();
            }

            @Override
            public void onFinished() {
                super.onFinished();
                myMain.closeDialog();
            }
        });
    }

    public void home4getData() {
        if (MyApplication.getInstance().userBean != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("userId", MyApplication.getInstance().userBean.getUserId());
            myMain.showDialog();
            XUtil.Post(ConfigUtil.CART, map, new MyCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    Log.i(TAG, "onSuccess: home4getData" + result);
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        JSONArray array = jsonObject.optJSONArray("goods");
                        shopList.clear();
                        for (int i = 0; i < array.length(); i++) {
                            ShoppingBean bean = new ShoppingBean();
                            bean = new Gson().fromJson(array.optJSONObject(i).toString(), ShoppingBean.class);
                            shopList.add(bean);
                        }
                        isAllSelect = false;
                        setAllSelect();
                        onHas();
                        mAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFinished() {
                    super.onFinished();
                    myMain.closeDialog();
                }
            });
        }

    }

    /**
     * ----更新总价格
     */

    private int allNum;
    private double totalPrice;
    private String allPrice;

    private void updateAllPrice() {

        allNum = 0;
        totalPrice = 0.00;
        //购物车无商品
        if (shopList.size() == 0) {
            tv_all_price.setText("¥0.00");
            return;
        }

        for (int i = 0; i < shopList.size(); i++) {
            if (shopList.get(i).isSelect()) {
                int num = Integer.parseInt(shopList.get(i).getGoodNumber());
                double price = Double.parseDouble(shopList.get(i).getGoodPrice());

                allNum = allNum + num;
                totalPrice = totalPrice + (num * price);

            }
        }
        allPrice = String.format("%.2f", totalPrice);//格式化double类型，保留小数点后两位，防止出现.99999999现象

        if (allNum == 0) {
            tv_all_price.setText("¥0.00");
        } else {
            tv_all_price.setText("¥" + allPrice);
        }

    }

}
